package dicebot.tools.dice;

import java.util.ArrayList;
import java.util.List;

public class Dice extends DiceExpression {

    public static int rand (int size) {
        return 1 + (int) (Math.random() * size);
    }

    public DiceExpression number, size;

    @Override
    public DiceExpression simplify() throws Exception {
        if (number instanceof Number && size instanceof Number) {
            int n = ((Number) number).value;
            int s = ((Number) size).value;
            if (n > (Math.random() * 100) + 100) {
                throw new LargeDiceNumberException();
            }
            if (n < 0) {
                throw new NegativeDiceNumberException();
            }
            if (s > (Math.random() * 1000) + 1000) {
                throw new LargeDiceSizeException();
            }
            if (s <= 0) {
                throw new ZeroOrNegativeDiceSizeException();
            }
            if (n == 0) {
                return new Number(0);
            }
            if (n == 1) {
                return new Number(rand(s));
            }
            List<DiceExpression> list = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                list.add(new Number(rand(s)));
            }
            return new LongAdd(list);
        } else {
            number = number.simplify();
            size = size.simplify();
            return this;
        }
    }

    public Dice (DiceExpression number, DiceExpression size) {
        this.number = number;
        this.size = size;
    }

    @Override
    public String toString() {
        String s1 = number.toString();
        if (!(number instanceof Number && ((Number) number).value > 0)) {
            s1 = "(" + s1 + ")";
        }
        String s2 = size.toString();
        if (!(size instanceof Number && ((Number) size).value > 0)) {
            s2 = "(" + s2 + ")";
        }
        return s1 + "d" + s2;
    }

    @Override
    public String toStringWithSign() {
        return "+" + toString();
    }

    static class DiceException extends Exception {}

    static class NegativeDiceNumberException extends DiceException {
        @Override
        public String getMessage() {
            return "没有骰子可以掷! ";
        }
    }
    static class LargeDiceNumberException extends DiceException {
        @Override
        public String getMessage() {
            return "菲琳被骰子淹没了! ";
        }
    }
    static class ZeroOrNegativeDiceSizeException extends DiceException {
        @Override
        public String getMessage() {
            return "是不存在的骰子呢! ";
        }
    }
    static class LargeDiceSizeException extends DiceException {
        @Override
        public String getMessage() {
            return "菲琳搬不动这个骰子...";
        }
    }
}